<template>
  <!-- 添加网址弹窗 -->
  <el-dialog v-model="visible" title="添加应用" width="500">
    <el-form ref="formRef" :model="form" label-position="left" :rules="rules">
      <el-form-item prop="name">
        <el-input v-model="form.name" placeholder="请输入网页名称" clearable />
      </el-form-item>
      <el-form-item prop="url">
        <el-input v-model="form.url" placeholder="请输入正确网址" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="onCancle(formRef)">取消</el-button>
        <el-button type="primary" @click="onConfirm(formRef)"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  url: {
    type: String,
    default: "",
  },
  name: {
    type: String,
    default: "",
  },
});

// 可见性
const visible = ref(false);
const emit = defineEmits(["cancle", "confirm"]);

const formRef = ref();

const form = defineModel({ default: () => ({ url: "", name: "" }) });

const rules = ref({
  url: [
    { required: true, message: "请输入网址", trigger: "blur" },
    { type: "url", message: "请输入正确的网址", trigger: ["blur", "change"] },
  ],
  name: [{ required: true, message: "请输入网页名称", trigger: "blur" }],
});

// 取消
const onCancle = () => {
  visible.value = false;
};

// 确定
const onConfirm = async (formEl) => {
  if (!formEl) return;

  await formEl.validate((valid, fields) => {
    if (valid) {
      visible.value = false;
      emit("confirm", form.value);
    } else {
      fields?.url?.forEach((message) => {
        ElMessage.error(message);
      });
    }
  });
};

const open = () => {
  visible.value = true;
};

defineExpose({
  open,
});
</script>
<style scoped lang="scss"></style>
